package main

import (
	"fmt"
	"io"
	"net"
	"os"
	"time"
)

func sendFile(conn net.Conn, file string, size int64)  {

	now := time.Now().Unix()

	f, err := os.Open(file)
	if err != nil {
		fmt.Println("os.Open err = ", err)
		return
	}
	defer f.Close()

	var buf = make([]byte, 1024 * 4)
	var hasSend int64 = 0
	var percent float64 = 0
	for {
		n, err := f.Read(buf)
		if err != nil {
			if err == io.EOF {
				end := time.Now().Unix()
				diff := end - now
				fmt.Println("文件发送完毕,耗时:", diff, "s")
			} else {
				fmt.Println("f.Read err = ", err)
			}

			return
		}

		n, err = conn.Write(buf[:n])
		if err != nil {
			fmt.Println("conn.Write err = ", err)
			return
		}
		hasSend += int64(n)
		currentPercent := float64(hasSend)/float64(size) * 100;
		if currentPercent - percent > 0.05 {
			percent = currentPercent
			fmt.Printf("当前进度: %2.2f\n", currentPercent)
		}
	}


}

func main() {
	fmt.Println("请输入需要传输的文件")
	var path string
	fmt.Scan(&path)

	//获取文件名
	info, err := os.Stat(path)
	if err != nil {
		fmt.Println("os.Stat err = ", err)
		return
	}

	//连接服务器,发送文件名
	conn, err := net.Dial("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("net.Dial err = ", err)
		return;
	}
	defer conn.Close()

	conn.Write([]byte(info.Name()))


	//接收服务器内容
	buf := make([]byte, 1024)
	n, err := conn.Read(buf)
	if err != nil {
		fmt.Println("conn.Read err = ", err)
		return
	}

	if "ok" == string(buf[:n]) {
		//发送文件内容
		sendFile(conn, path, info.Size())
	}
}
